import java.util.ArrayList;

public class FuIParser {
	private ArrayList<String> vars;
	private ArrayList<String> vals;
	private ArrayList<String> funcn;
	private ArrayList<String> funcv;
	private String msg;
	public FuIParser(String m) {
		vars = new ArrayList<String>();
		vals = new ArrayList<String>();
		funcn = new ArrayList<String>();
		funcv = new ArrayList<String>();
		msg = m;
	}
	public String Message() {
		return msg;
	}
	public ArrayList<String> getConstVals() {
		return vals;
	}
	public ArrayList<String> getConstVars() {
		return vars;
	}
	public ArrayList<String> getFuncVars() {
		return funcn;
	}
	public ArrayList<String> getFuncVals() {
		return funcv;
	}
	public void delFunc() {
		funcn.clear();
		funcv.clear();
	}
	public void delVars() {
		vars.clear();
		vals.clear();
	}
	public String Parse(String Line) {
		String Ret = new String();
		if(Line.trim().isEmpty()) {
			return msg;
		}
		if(Line.length() < 6) {
			Line = Line + "     ";
		}
		if(Line.substring(0,6).compareTo("const ") == 0) {
			Line = Line.trim();
			//variable 
			String var1 = Line.substring(5,Line.indexOf("=")-1);
			vars.add(var1.trim().toUpperCase());
			String val1 = "(" + Line.substring(Line.indexOf("=")+1).trim() + ")";
			vals.add(val1);
			System.out.printf(msg);
		}
		else if(Line.substring(0,4).compareTo("def ") == 0) {
			Line = Line.trim();
			//funkcije
			String var1 = Line.substring(3,Line.indexOf("="));
			funcn.add(var1.trim().toLowerCase());
			String val1 = Line.substring(Line.indexOf("=")+1).trim();
			funcv.add(val1.trim());
			System.out.printf(msg);
		}
		else if(Line.substring(0,6).compareTo("range(") == 0 || Line.substring(0,6).compareTo("range ") == 0) {
			String ins = Line.substring(Line.indexOf("(")+1,Line.indexOf(")"));
			String[] ranges = ins.split(",");
			int from = Integer.parseInt(ranges[0].trim());
			int to = Integer.parseInt(ranges[1].trim());
			String function1 = Line.substring(Line.indexOf(")")+1);
			function1 = function1.trim();
			String funcvA;
			try {
				funcvA = funcv.get(funcn.indexOf(function1));
			}
			catch(Exception e) {
				funcvA = "x*(1)";
			}
			String buf = new String();
			for(int i = from;i <= to;i++)
			{
				String lini = function1+"("+i+")";
				lini = FuParser.functionized(lini,function1,funcvA);
				lini = FuCore.Eval(lini);
				buf += lini + "\n";
			}
			return buf;
		}
		else if(Line.substring(0,2).compareTo("//") == 0) {
			//do nothing
			System.out.printf(msg);
		}
		else {
			Line = Line.trim();
			for(int i = 0;i < vars.size();i++) {
				Line = Line.replace(vars.get(i).trim(),vals.get(i));
			}
			for(int i = 0;i < funcn.size();i++) {
				if(Line.contains(funcn.get(i))) {
					for(int x = 0;x < Line.length();x++) {
						Line = FuParser.functionized(Line,funcn.get(i),funcv.get(i));
					}
				}
			}
			Ret = FuCore.Eval(Line);
		}
		return Ret;
	}
}
